package vn.gg.network;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.google.gson.Gson;

import vn.gg.util.Log;

/**
 * Xu li meesage nhan duoc tu client.
 * 
 * @author truongps
 * 
 */
class ServerDecoder extends CumulativeProtocolDecoder {

	final static String TAG = "ServerDecoder";
	
	final static Gson GSON = new Gson();

	// public static final CharsetDecoder decoder = (Charset.forName("UTF-8"))
	// .newDecoder();

	@Override
	protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer,
			ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
		try {
			if (ioBuffer.prefixedDataAvailable(4, Integer.MAX_VALUE)) {
				int length = ioBuffer.getInt();
				Log.log(TAG, "Received Message Length: " + length);
				byte[] bytes = new byte[length];
				ioBuffer.get(bytes);
				String jsonString = new String(bytes, "UTF-8");
				Log.log(TAG, "Received Message Data: " + jsonString);
				Message message = GSON.fromJson(jsonString, Message.class);
				protocolDecoderOutput.write(message);
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
